//
//  CoverFlowViewController.m
//  KeYin
//
//  Created by Sean Chen on 5/28/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CoverFlowViewController.h"


@implementation CoverFlowViewController

@synthesize periodicals;
@synthesize covers;
@synthesize splash;
@synthesize flowCoverView;
@synthesize processViewController;
@synthesize spinner;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [periodicals release];
    [covers release];
    [splash release];
    [flowCoverView release];
    [processViewController release];
    [spinner release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"新刊推荐";
    
    self.splash = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Default.png"]];
    [[UIApplication sharedApplication].keyWindow addSubview:splash];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"更多精彩" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    self.navigationItem.rightBarButtonItem = item;
    [item release];
    
    self.covers = [[NSMutableArray alloc] init];
    
    NSString *URL = @"http://www.keyin.cn/ipad/new_magazines.php";
    
    TTURLRequest *request = [TTURLRequest requestWithURL:URL delegate:self];
    
    TTURLJSONResponse *response = [[TTURLJSONResponse alloc] init];
    request.response = response;
    [response release];
    
    [request send];
    
    [spinner startAnimating];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dismiss {
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma FlowCoverViewDelegate

- (int)flowCoverNumberImages:(FlowCoverView *)view
{
	return periodicals.count;
}

- (UIImage *)flowCover:(FlowCoverView *)view cover:(int)image
{
    if (covers && image < covers.count && [covers objectAtIndex:image]) {
        return [covers objectAtIndex:image];
    } else {
        return [UIImage imageNamed:@"Default.png"]; // should never happen
    }
}

- (void)flowCover:(FlowCoverView *)view didSelect:(int)image
{
    selectedPeriodicalIndex = image;
    
    NSDictionary *periodical = [periodicals objectAtIndex:image];
    
    if ([M13FileManager exits:periodical inFile:kFileNamePeriodicals]) {
        [self readSelectedPeriodical];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"确认要下载？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"下载", nil];
        [alert setTag:1];
        [alert show];
        [alert release];
    }
}

#pragma mark - TTURLRequestDelegate

- (void)requestDidFinishLoad:(TTURLRequest*)request {
    TTURLJSONResponse *response = request.response;
    
    NSDictionary *rootDict = response.rootObject;
    NSDictionary *result = [rootDict objectForKey:@"result"];
    
    NSArray *entries = [result objectForKey:@"new_magazines"];
    
    self.periodicals = entries;
    
    //[self.flowCoverView layoutSubviews];
    [self performSelectorInBackground:@selector(downloadCovers) withObject:nil];
}

- (void)request:(TTURLRequest*)request didFailLoadWithError:(NSError*)error {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"联网失败 请稍后再试" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [alert show];
    [alert release];
    
    [spinner stopAnimating];
}

#pragma mark -
#pragma mark private

- (void)downloadCovers {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    loadingCoverIndex = 0;
    BOOL success = YES;
    
    for (NSDictionary *dict in periodicals) {
        NSURL *URL = [NSURL URLWithString:[dict objectForKey:@"cover_img"]];
        NSData *data = [NSData dataWithContentsOfURL:URL];
        
        if (!data) {
            success = NO;
            continue;
        }
        UIImage *img = [UIImage imageWithData:data];
        [covers addObject:img];
    }
    
//    if (!success) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"联网失败 请稍后再试" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//    }
    
    [pool release];
    
    [self performSelectorOnMainThread:@selector(generateCovers) withObject:nil waitUntilDone:NO];
}

- (void)generateCovers {
    
    [splash removeFromSuperview];
    
    CGRect rect = self.view.frame;
    rect.origin.x = -80;
    rect.size.width = 480;
    rect.origin.y = -160;
    rect.size.height = 640;
    self.flowCoverView = [[FlowCoverView alloc] initWithFrame:rect];
    flowCoverView.delegate = self;
    flowCoverView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:flowCoverView];
    [self.view sendSubviewToBack:flowCoverView];
    
    [spinner stopAnimating];
}

- (void)downloadSelectedPeriodical {
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    NSDictionary *periodical = [periodicals objectAtIndex:selectedPeriodicalIndex];
    NSString *src;
    NSString *ID = [periodical objectForKey:@"periodical_id"];
    NSString *pageName;
    NSUInteger pages = [[periodical objectForKey:@"pages"] integerValue];
    
    loadingPageIndex = 0;
    BOOL success = YES;
    
    while (loadingPageIndex < pages) {
        
        src = [NSString stringWithFormat:@"http://www.keyin.cn/ipad/get_magazine.php?periodical_id=%@&page=%d", ID, loadingPageIndex + 1];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:src]];
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        if (!data) {
            success = NO;
            break;
        }
        pageName = [NSString stringWithFormat:kFileNamePage, ID, loadingPageIndex];
        if (![data writeToFile:[M13FileManager filePathWithFileName:pageName] atomically:YES]) {
            //TODO handle the error
        }
        
        loadingPageIndex++;
        
        [self performSelectorOnMainThread:@selector(updateProgress:) withObject:[NSNumber numberWithFloat:(CGFloat)loadingPageIndex/pages] waitUntilDone:NO];
    }
    
    if (success) {
        [M13FileManager add:periodical toFile:kFileNamePeriodicals];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"下载失败 请稍后再试" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [alert show];
        [alert release];
        
        [processViewController.view removeFromSuperview];
    }
    
    [pool release];
}

- (void)readSelectedPeriodical {
    NSDictionary *periodical = [periodicals objectAtIndex:selectedPeriodicalIndex];

    ContentViewController *detailViewController = [[ContentViewController alloc] initWithPeriodical:periodical];
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

- (void)updateProgress:(NSNumber *)progress {
    
    [processViewController updateProgress:[progress floatValue]];
    
    if ([progress integerValue] == 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"下载完成 立即阅读？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"阅读", nil];
        [alert setTag:2];
        [alert show];
        [alert release];
    }
}

#pragma mark -
#pragma UIAlertViewDelegate

//DownloadingConfirmAlert Tag = 1,
//ReadingConfirmAlert Tag = 2
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if ([alertView tag] == 1 && buttonIndex == 1) {
        
        self.processViewController = [[ProcessViewController alloc] initWithNibName:@"ProcessViewController" bundle:nil];
        processViewController.view.frame = CGRectMake(0.0, 20.0, 320.0, 460.0);
        UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
        [window addSubview:processViewController.view];
        
        [self performSelectorInBackground:@selector(downloadSelectedPeriodical) withObject:nil];
        
    } else if ([alertView tag] == 2) {
        
        if (buttonIndex == 1) {
            [self readSelectedPeriodical];
        }
        
        [processViewController.view removeFromSuperview];
    }
}

@end
